import { createPinia } from 'pinia';
import { createPersistedState } from 'pinia-plugin-persistedstate'; // 数据持久化
import SecureLS from 'secure-ls';

/** uni本地数据缓存 */
const uniStorage = {
  clear: uni.clearStorageSync,
  getItem: uni.getStorageSync,
  // key(index: number): string | null,
  removeItem: uni.removeStorageSync,
  setItem: uni.setStorageSync,
};

const ls = new SecureLS({
  encryptionSecret: import.meta.env.VITE_STORE_SECURE_KEY || 'p@ssw0rd', // 加密秘钥
  encryptionNamespace: '', // 加密命名空间
  isCompression: true, // 是否压缩
  encodingType: 'aes', // 编码类型
  // @ts-ignore secure-ls does not have a type definition for this
  storage: uniStorage, // 存储
  metaKey: `${import.meta.env.VITE_UNI_APPID}-secure-meta`, // meta密钥
});

const store = createPinia();
store.use(
  createPersistedState({
    // key $appName-$store.id
    key: (storeKey) => `${import.meta.env.VITE_UNI_APPID}-${storeKey}`,
    storage: import.meta.env.DEV
      ? uniStorage
      : {
          getItem(key) {
            return ls.get(key);
          },
          setItem(key, value) {
            ls.set(key, value);
          },
        },
  }),
);

export default store;
